package top.codedance.iotp.client.plugins.sync.udp.listenner;

import cd.io.netty.buffer.ByteBuf;
import cd.io.netty.channel.ChannelHandlerContext;
import cd.io.netty.channel.SimpleChannelInboundHandler;
import cd.io.netty.channel.socket.DatagramPacket;
import top.codedance.iotp.client.ClientApplication;
import top.codedance.iotp.client.plugins.sync.udp.UdpClient;
import top.codedance.iotp.client.plugins.sync.udp.UdpExecuterImpl;
import org.apache.log4j.Logger;

import java.net.InetSocketAddress;

public class UdpListenner extends SimpleChannelInboundHandler<DatagramPacket> {
    private Logger logger = ClientApplication.getLogger(UdpExecuterImpl.class);
    private UdpClient udpClient;
    public UdpListenner(UdpClient udpClient){
        this.udpClient = udpClient;
    }

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
        InetSocketAddress sender = datagramPacket.sender();
        String ip = sender.getAddress().getHostAddress();
        logger.debug("Reqeust IP: " + ip);
        ByteBuf buf = datagramPacket.copy().content();
        try {
            byte[] data = new byte[buf.readableBytes()];
            buf.readBytes(data);
            udpClient.appendResult(data);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
